#!/bin/bash

set -Eeuo pipefail
shopt -s inherit_errexit

# expects the following variables defined in the environment:
# - BUCKET_CONFIG_NAME: name of env variable with bucket configuration
# - POSTGRESQL_{USER,PASSWORD,HOST,DATABASE}: PostgreSQL

# shellcheck disable=SC1091
. cki_utils.sh

# shellcheck disable=SC2154
cki_parse_bucket_spec "${BUCKET_CONFIG_NAME}"
# shellcheck disable=SC2154
AWS_S3=(aws s3 --endpoint "${AWS_ENDPOINT}")
# shellcheck disable=SC2154
S3_PATH="s3://${AWS_BUCKET}/${AWS_BUCKET_PATH}"

DATA_PATH="/tmp/dump"
mkdir -p "${DATA_PATH}"

cki_echo_yellow "Retrieving lists of previous backups..."
S3_LIST="/tmp/s3-list.txt"
("${AWS_S3[@]}" ls "${S3_PATH}" || true) \
    | awk '{print $NF}' \
    | sort \
    > "${S3_LIST}"

# shellcheck disable=SC2248
select NAME in $(cat ${S3_LIST}); do
    "${AWS_S3[@]}" cp "${S3_PATH}${NAME}" - | gzip -d > "${DATA_PATH}/backup.sql"

    # shellcheck disable=SC2154
    (
        echo 'DO $$ DECLARE'
        echo '    r RECORD;'
        echo 'BEGIN'
        echo "    FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public') LOOP"
        echo "        EXECUTE 'DROP TABLE ' || quote_ident(r.tablename) || ' CASCADE';"
        echo '    END LOOP;'
        echo 'END $$;'
        cat "${DATA_PATH}/backup.sql"
    ) | PGPASSWORD=${POSTGRESQL_PASSWORD} psql --host "${POSTGRESQL_HOST}" --username "${POSTGRESQL_USER}" --dbname "${POSTGRESQL_DATABASE}"

    break
done
